﻿using AutoMapper;
using MediatR;
using SqlSugar;
using WarehouseManagement.Application.Command.ShipApplyCommand;
using WarehouseManagement.Domain.DTO.ShipApply;
using WarehouseManagement.Domain.Entity;
using WarehouseManagement.Infrstructre.Interface;
namespace WarehouseManagement.Application.CommandHandler.ShipApplyCommandHandlers
{
    public class UptShipCommandHandlers:IRequestHandler<UptShipCommand,int>
    {
        private readonly IShipRequestRepository _shipRequestRepository;
        private readonly IShipRequestProRepository _shipRequestProRepository;
        private readonly IMapper _mapper;
        ISqlSugarClient _db;


        public UptShipCommandHandlers(IShipRequestRepository shipRequestRepository, IShipRequestProRepository shipRequestProRepository, IMapper mapper, ISqlSugarClient db)
        {
            _shipRequestRepository = shipRequestRepository;
            _shipRequestProRepository = shipRequestProRepository;
            _mapper = mapper;
            _db = db;
        }

        public async Task<int> Handle(UptShipCommand request, CancellationToken cancellationToken)
        {


            _db.Ado.BeginTran();
            try
            {
                var query = _mapper.Map<ShippRequestApp>(request.dto);
                var res = await _shipRequestRepository.UpdateAsync(query);

                var query1 = (await _shipRequestProRepository.GetAll()).Where(x => x.SRANumber == request.dto.SRANumber).ToList();

                var res1 = await _shipRequestProRepository.DelRange(query1);

                foreach (var item in request.dto.detail)
                {
                    ShipProductApp pro = new ShipProductApp()
                    {
                        ShipProductAppId = item.ShipProductAppId,
                        ProNum = item.ProNum,
                        PSpec = item.PSpec,
                        PUnit = item.PUnit,
                        Remark = item.Remark,
                        SRANumber = query.SRANumber,
                        PackMethod = item.PackMethod,
                        PName = item.PName,
                        PNumber = item.PNumber,
                        ProductId = item.ProductId


                    };
                    await _shipRequestProRepository.AddAsync(pro);
                }

                _db.Ado.CommitTran();
                return 1;
            }
            catch (Exception ex)
            {

                _db.Ado.RollbackTran();
                throw;
            }

            
        }
    }
}
